class Solution {
public:
    int lenLongestFibSubseq(vector<int>& arr) {
        map<int,int> arrMap;
        vector<vector<int>> map(arr.size(),vector<int>(arr.size(),-1));

        for(int i = 0; i < arr.size(); ++i){
            arrMap.insert({arr[i],i});
        }
        for(int i = 0; i < arr.size() - 2; ++i){
            for(int j = i + 1; j < arr.size() - 1; ++j){
                int add = arr[i] + arr[j];

                auto it = arrMap.find(add);
                if (it != arrMap.end()){
                    int k = it->second;
                    map[i][j] = k;
                }
            }
        }
        
        int max_length = 0;

        for(int i = map.size() - 1; i >= 0; --i){
            for(int j = map.size() - 1; j > i; --j){
                int k = map[i][j];

                if(k == -1){
                    continue;
                }

                if(map[j][k] == -1){
                    map[i][j] = 3;
                }else{
                    map[i][j] = map[j][k] + 1;
                }
                
                max_length = max(max_length,map[i][j]);
            }
        }
        
        return max_length;
    }
};